//
//  VKAuth.m
//  VKChat
//
//  Created by Максим Бризинский on 23.01.11.
//  Copyright 2011 БГУИР. All rights reserved.
//

#import "VKAuth.h"
#import "SBJsonParser.h"


@implementation VKAuth
@synthesize session = _session;
@synthesize delegate = _delegate;

#pragma mark -
#pragma mark Load Methods
-(void)getSession {
	//создаем урл
	NSURL* loginUrl = [[NSURL alloc] initWithString:@"http://vkontakte.ru/login.php"];
	
	//создаем запрос серверу на базе нашего урла
	NSMutableURLRequest *loginRequest = [[NSMutableURLRequest alloc] initWithURL:loginUrl];
	[loginRequest setHTTPMethod:@"POST"];
	[loginRequest setHTTPBody:[@"app=1951595&layout=popup&type=browser&settings=5122" dataUsingEncoding:NSUTF8StringEncoding]];
	
	//отправляем наш запрос через браузер
	[_webView setFrameLoadDelegate:self];
	[_webView.mainFrame loadRequest: loginRequest];
	//NSLog(@"VKApi: getSession Done");
}
#pragma mark -
#pragma mark WebView Delegate
- (void)webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame {
	//NSLog(@"Finish Loading");
	
	//получаем урл на который нас перенаправил сервер
	NSString* redirectUrl = [sender mainFrameURL];
	
	NSRange compareRange = [redirectUrl rangeOfString:@"login_success.html"];
	
	//если в урле содержится строка login_success то достаем параметры переданные сервером
	if (compareRange.location != NSNotFound) {
		NSLog(@"VKAuth: Login succsess");
		
		//находим где сервер передает параметры в json-строке после "session="
		NSRange calcPositionRange = [redirectUrl rangeOfString:@"="];
		if (calcPositionRange.location != NSNotFound) {
			NSString *jsonString = [redirectUrl substringFromIndex:(calcPositionRange.location + 1)];
			//NSLog(@"%@",jsonString);
			
			//исправляем недопустимые символы в строке и получаем готовую json строку
			jsonString = [self fixUrlString:jsonString];
			//NSLog(@"%@",jsonString);
			
			//разбираем строку в словарь парсером
			SBJsonParser* parser = [[SBJsonParser alloc] init];
			NSDictionary* dict = [parser objectWithString:jsonString];
			[parser release];
			
			_session.expire = [[dict objectForKey:@"expire"] intValue];
			_session.mid = [[dict objectForKey:@"mid"] intValue];
			_session.secret = [[dict objectForKey:@"secret"] retain];
			_session.sid = [[dict objectForKey:@"sid"] retain];
			
			//[dict release];
			
			[_delegate vkAuthDidSuccess:_session];
			
		} else {
			NSLog(@"VKApi: Unknow error");
			[_delegate vkAuthDidFail];
		}
			
		
	} else {
		NSLog(@"VKApi: Login failure");
		[_delegate vkAuthDidFail];
	}

	
}

- (void)webView:(WebView *)sender didStartProvisionalLoadForFrame:(WebFrame *)frame {
	//NSLog(@"Start Loading");
}

#pragma mark -
#pragma mark Working with string
-(NSString*)fixUrlString:(NSString*) urlString {
	urlString = [urlString stringByReplacingOccurrencesOfString:@"%22" withString:@"\""];
	urlString = [urlString stringByReplacingOccurrencesOfString:@"%7B" withString:@"{"];
	urlString = [urlString stringByReplacingOccurrencesOfString:@"%7D" withString:@"}"];
	urlString = [urlString stringByReplacingOccurrencesOfString:@"%3A" withString:@":"];
	urlString = [urlString stringByReplacingOccurrencesOfString:@"%2C" withString:@","];
	return urlString;
	
}

#pragma mark -
#pragma mark Init methods
-(id)initWithWebView:(WebView *)webView {
	self = [super init];
	if(self != nil) {
		_webView = [webView retain];
	}
	return self;
}

#pragma mark -
#pragma mark Mamory managmemet methods
-(void) dealloc {
	//[_webView release];
	_webView = nil;
 	[super dealloc];
}

@end
